import { Table, TableProps } from 'antd'
import { TableRowSelection } from 'antd/lib/table/interface'
import React, { useImperativeHandle, useState } from 'react'

export interface PaginationType {
  pageNumber: number
  pageSize: number
  total: number
}

export interface StandardTableRef {
  /** 数据源 */
  dataSource: any[]
  /** 设置数据源 */
  setDataSource: (dataSource: any[]) => void
  /** 选择项键集合 */
  selectedRowKeys: React.Key[]
  /** 清空选择项 */
  clearSelection: () => void
  /** 选择项 */
  selectedRows: any[]
}

export interface StandardTableProps
  extends Omit<TableProps, 'dataSource' | 'rowSelection'> {
  /** 实例 */
  ref?: React.RefObject<StandardTableRef>
  /** 选择配置，内部管理被选择的值 */
  rowSelection?: Omit<TableRowSelection<any>, 'selectedRowKeys'>
}

/**
 * 标准表格
 */
export const StandardTable = (props: StandardTableProps) => {
  const [dataSource, setDataSource] = useState<any[]>([])
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const [selectedRows, setSelectedRows] = useState<any[]>([])

  const { ref: propRef, ...restProps } = props

  useImperativeHandle(propRef, () => ({
    dataSource,
    setDataSource,
    selectedRowKeys,
    selectedRows,
    clearSelection: () => {
      setSelectedRowKeys([])
      setSelectedRows([])
    },
  }))

  /**
   * 覆盖选择行配置
   */
  const rowSelection: TableRowSelection<any> = {
    ...props,
    selectedRowKeys: selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows, info) => {
      setSelectedRowKeys(selectedRowKeys)
      setSelectedRows(selectedRows)
      props?.rowSelection?.onChange?.(selectedRowKeys, selectedRows, info)
    },
  }

  return (
    <Table {...restProps} dataSource={dataSource} rowSelection={rowSelection} />
  )
}
